<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class LogRecordRequest
{
    private const LOCK_TIMEOUT = 5;

    private const IGNORE_URL = [
        '*/v1/notice',
    ];

    private const IGNORE_ROUTE = [

    ];

    /**
     * 非 GET 请求时, 尝试获得锁
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 配置开启
        if (!config('admin.enable_api_debug_log')) return $next($request);

        // 忽略URL
        foreach (self::IGNORE_URL as $rule) {
            if ($request->is($rule)) return $next($request);
        }
        // 忽略路由名
        foreach (self::IGNORE_ROUTE as $rule) {
            if ($request->routeIs($rule)) return $next($request);
        }

        $response = $next($request);
        // 日志记录
        $responseStr = $response;
        if ($response instanceof \Illuminate\Http\Response) {
            $responseStr = $response->getOriginalContent();
        }

        $key = sprintf("%s:%s:%s", $request->getRequestUri(), $request->getMethod(), getClientIp());

        $user = $request->user();
        if ($user) $key = sprintf("%s:%d", $key, $user->id);

        info("[{$key}]\n", [
            'request' => $request->all(),
            'response' => $responseStr
        ]);
        return $response;
    }
}
